#!/bin/bash
set -euo pipefail  # 严格错误检查

# 配置区 ===================================================================
GIT_REPO="https://gitee.com/hehe8/exam-pro.git"
GIT_BRANCH="${GIT_BRANCH:-master-pro}"  # 支持环境变量覆盖
BUILD_MODULE="${BUILD_MODULE}"           # 必须传入模块名

# 端口映射配置
declare -A PORT_MAP=(
  ["exam-pro-web"]=80
  ["exam-pro-gateway"]=18000
  ["exam-pro-user"]=18001
  ["exam-pro-question"]=18002
  ["exam-pro-paper"]=18003
  ["exam-pro-exam"]=18004
  ["exam-pro-course"]=18005
)

# 模块列表
MODULES=(
  "exam-pro-web"
  "exam-pro-gateway"
  "exam-pro-user"
  "exam-pro-question"
  "exam-pro-paper"
  "exam-pro-exam"
  "exam-pro-course"
)

# 函数定义 =================================================================
# 显示菜单并获取选择
select_module() {
  echo "请选择要部署的项目："
  for i in "${!MODULES[@]}"; do
    printf "  %d: %s\n" "$((i+1))" "${MODULES[$i]}"
  done

  while true; do
    read -p " 输入编号: " choice
    # 验证输入是否为数字且在有效范围内
    if [[ $choice =~ ^[1-7]$ ]]; then
      BUILD_MODULE="${MODULES[$((choice-1))]}"
      echo "已选择: $BUILD_MODULE"
      return
    else
      echo "无效输入，请输入1-7的数字"
    fi
  done
}

# 前置依赖检查
check_deps() {
#  command -v git >/dev/null || { echo "✗ 缺少git"; exit 1; }
  command -v mvn >/dev/null || { echo "✗ 缺少Maven"; exit 1; }
  command -v docker >/dev/null || { echo "✗ 缺少Docker"; exit 1; }
  docker network inspect exam-pro-net &>/dev/null ||
    docker network create exam-pro-net
}

pull_code() {
  echo ">>> 拉取代码 ($GIT_BRANCH)..."
  git clone -b "$GIT_BRANCH" "$GIT_REPO" "./"
}

build_module() {
  echo ">>> 编译模块 $BUILD_MODULE"

  if [[ "$BUILD_MODULE" != "exam-pro-web" ]]; then
    cd "$BUILD_MODULE"
    mvn clean package -DskipTests -s /home/hehehe/.m2/settings.xml
  else
    cd "exam-pro-web/exam-pro"
  fi
}

docker_deploy() {
  echo ">>> 部署 $BUILD_MODULE"

  # 智能定位Dockerfile文件
  if [[ -f "$BUILD_MODULE-web/Dockerfile" ]]; then
    cd "$BUILD_MODULE-web"
  fi

  # Docker操作流程
  docker stop "$BUILD_MODULE" &>/dev/null || true
  docker rm "$BUILD_MODULE" &>/dev/null || true
  docker build -t "$BUILD_MODULE" .

  # 动态端口映射
  if [[ -v PORT_MAP["$BUILD_MODULE"] ]]; then
    port_flag="-p ${PORT_MAP[$BUILD_MODULE]}:${PORT_MAP[$BUILD_MODULE]}"
  fi

  docker run -d \
    --name "$BUILD_MODULE" \
    --network exam-pro-net \
    ${port_flag:-} \
    "$BUILD_MODULE"
}

# 主流程 ==================================================================
main() {
  select_module
  check_deps
#  pull_code
  build_module
  docker_deploy
  
  echo ">>> 部署完成！访问地址:"
  echo " - 容器: docker ps | grep $BUILD_MODULE"
  echo " - 日志: docker logs $BUILD_MODULE"
  [[ -v PORT_MAP["$BUILD_MODULE"] ]] && 
    echo " - 端口: http://$(hostname -I | awk '{print $1}'):${PORT_MAP[$BUILD_MODULE]}"
}

main